package com.tg.app.activity.device.add;

import static com.tg.app.activity.device.DeviceSettingsActivity.EXT_DEVICE_INFO;

import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.Window;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.base.BaseActivity;
import com.tange.base.toolkit.StringUtils;
import com.tange.feature.data.structure.DeviceTypeBean;
import com.tg.app.R;
import com.tg.app.activity.device.DeviceListActivity;
import com.tg.app.activity.device.binding.DeviceTypeQuery;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.util.LogUtils;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.helper.DeviceTypeHelper;

import java.util.HashMap;

/**
 * 技术方案： 改造为 通用性 更强的页面。
 * 1. 根据 uuid ，使用 DeviceTypeQuery 查询设备类型 （不要从其他页面透传，容易增加耦合度，而且所有添加路径都要传、麻烦）
 * 2. 根据设备类型，展示不同的文案
 * 3. 所有的添加失败页面都用这个，把其他已有的页面，比如 ApFailedActivityEx 删掉。
 */
public  class GlobalAddFailedActivity extends BaseActivity {

    private String mUUID;
    private String mType;
    private boolean mIsBluetoothDevice = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        if (getIntent() != null) {
            mUUID = getIntent().getStringExtra(ApSetWifiActivityEx.EXT_WIFI_UUID);
            mType = getIntent().getStringExtra(ApSetWifiActivityEx.EXT_DEVICE_TYPE);
            mIsBluetoothDevice = getIntent().getBooleanExtra(ApSetWifiActivityEx.EXT_DEVICE_BLUETOOTH, false);
        }

        setContentView(R.layout.activity_add_device_failed);
        hideActionBar();
        initView();
        if (StringUtils.isEmpty(mType)){
            getDeviceType();
        }

        HashMap<String,String> map = new HashMap<>();
        map.put("mode","bind_app");
        map.put("event","bind_failed");
        LogUtils.uploadLog(map);
    }

    private String getFailedTip(){
        if (mIsBluetoothDevice){
            return ResourcesUtil.getString(R.string.please_lock_dell_bluetooth_ensure);
        }
        if (DeviceTypeHelper.isLamp(mType)
                || DeviceTypeHelper.isLpLockBell(mType)
                || DeviceTypeHelper.isActiveDoorBellDevice(mType)
                || DeviceTypeHelper.isWifiDevice(mType)
                || StringUtils.isEmpty(mType)){
            return ResourcesUtil.getString(R.string.please_add_device_faild_tip);
        }

        return ResourcesUtil.getString(R.string.please_add_4g_device_faild_tip);
    }

    private void updateFailedInfoFromType(){
        if (!StringUtils.isEmpty(mType)){
            setFailedTip();
        }
    }

    private void setFailedTip() {
        String tip = getFailedTip();
        TextView textView = findViewById(R.id.text_add_faild_tip);
        textView.setText(tip);
    }

    private void getDeviceType(){
        DeviceTypeQuery.create().request(mUUID, new DeviceTypeQuery.Callback() {
            @Override
            public void onSuccess(@NonNull DeviceTypeBean deviceTypeBean) {
                mType =  deviceTypeBean.getDevice_type();
                updateFailedInfoFromType();
            }

            @Override
            public void onUuidNotFound() {
            }

            @Override
            public void onError(int errorCode, String errorMsg) {
                setFailedTip();
            }
        });
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void initView() {

       findViewById(R.id.device_ap_add_back_to_home).setOnClickListener(v -> {
           // SDK 直接结束

           Intent intent = new Intent();
           intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP );
           intent.setClass(GlobalAddFailedActivity.this, DeviceListActivity.class);
           startActivity(intent);
           finish();
       });
        findViewById(R.id.device_ap_add_again).setOnClickListener(v -> {
            Intent  toAddChoose = new Intent(GlobalAddFailedActivity.this, ScanQrcodeActivity.class);
            startActivity(toAddChoose);
            finish();
        });


        TextView otherAdd = findViewById(R.id.text_add_other_type);
        otherAdd.setText(getAddDeviceClickableSpan(ResourcesUtil.getString(R.string.please_add_other_type), ResourcesUtil.getString(R.string.txt_add_other_type), false));
        otherAdd.setMovementMethod(LinkMovementMethod.getInstance());
        updateFailedInfoFromType();
        otherAdd.setVisibility(View.GONE);
    }


    @Override
    public void onBackPressed() {
    }


    public SpannableString getAddDeviceClickableSpan(String text, String clickText, final boolean resetDevice) {
        SpannableString spannableInfo = new SpannableString(text);
        class ClickableAddOtherType extends ClickableSpan implements View.OnClickListener {
            public ClickableAddOtherType() {}

            @Override
            public void onClick(@NonNull View v) {
                if (resetDevice && !(DeviceTypeHelper.isLockBell(mType) || DeviceTypeHelper.isDoorBell(mType))){
                    DeviceSettingsInfo info = getIntent().getParcelableExtra(EXT_DEVICE_INFO);
                    ActivityHelper.gotoResetDevice(GlobalAddFailedActivity.this, info);
                }else{
                    ActivityHelper.gotoAddDeviceHomePage(GlobalAddFailedActivity.this);
                }
            }

            @Override
            public void updateDrawState(@NonNull TextPaint ds) {
                super.updateDrawState(ds);
                ds.setColor(ResourcesUtil.getResources().getColor(com.module.appcommon.R.color.global_customize_fixed_color_link));       //设置文件颜色
                ds.setUnderlineText(true);      //设置下划线
            }
        }


        int pos1 = text.indexOf(clickText);

        if (pos1>0){
            spannableInfo.setSpan(new ClickableAddOtherType(), pos1, pos1 + clickText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            spannableInfo.setSpan(new ForegroundColorSpan(ResourcesUtil.getResources().getColor(R.color.global_customize_fixed_color_link)), pos1, pos1 + clickText.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        }

        return spannableInfo;
    }

}
